package crontab

import (
	"longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

func LiveCallback() {
	var liveCallBackList []*models_live.LiveCallbackStore
	var oneHourAgo = time.Now().Add(-time.Hour * 1) // 只处理1小时内的
	err := global.Live().Model(&models_live.LiveCallbackStore{}).Where("created_at >= ? and status = ?", oneHourAgo, cache.StartLive).Find(&liveCallBackList).Error
	if err != nil {
		global.Log.Errorf("err:%v", err)
		return
	}
	var tempLives []*models_live.Live
	err = global.Live().Model(&models_live.Live{}).Where("platform=?", 0).Find(&tempLives).Error
	if err != nil {
		global.Log.Errorf("err:%v", err)
		return
	}
	if len(tempLives) < 1 {
		return
	}
	streamMap := make(map[string]int)
	var streamIds []string
	for _, v := range tempLives {
		for _, l := range liveCallBackList {
			if v.Stream == l.StreamID && l.Status == int(cache.StartLive) {
				streamMap[l.StreamID] = int(cache.StartLive)
				l := &cache.AnchorLive{
					Anchorid: v.Anchorid,
					Liveid:   v.Liveid,
					Start:    time.Now().Format("2006-01-02 15:04:05"),
					Status:   cache.StartLive,
					Matchid:  v.Matchid,
					Nickname: v.AnchorName,
					Heat:     v.Hot,
				}
				cache.SetAnchorLive(v.Anchorid, l)
			}
		}
	}
	for stream := range streamMap {
		streamIds = append(streamIds, stream)
	}
	if len(streamIds) > 0 {
		err = global.Live().Model(&models_live.Live{}).Where("status = 0 and stream in ?", streamIds).Update("status", cache.StartLive).Error
		if err != nil {
			global.Log.Errorf("LiveCallback err:%v", err)
			return
		}
		global.Live().Model((&models_live.LiveCallbackStore{})).Where("stream_id in ?", streamIds).Update("status", -1)
	}
}
